package com.yupi.yupicturebackend.api.baidu.imageUnderstand.sub;

import cn.hutool.json.JSONObject;
import okhttp3.*;
import java.io.IOException;

public class ImageUnderstandingTaskCreator {
    private String accessToken;
    private final OkHttpClient httpClient;

    public ImageUnderstandingTaskCreator(String accessToken, OkHttpClient httpClient) {
        this.accessToken = accessToken;
        this.httpClient = httpClient;
    }

    public void updateAccessToken(String newAccessToken) {
        this.accessToken = newAccessToken;
    }

    public String createTask(String imageUrl, String question) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject requestBody = new JSONObject();
        requestBody.put("url", imageUrl);
        requestBody.put("question", question);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request?access_token=" + accessToken)
                .post(RequestBody.create(requestBody.toString(), mediaType))
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 检查 response.body() 是否为 null，避免 NullPointerException
            ResponseBody responseBodyObj = response.body();
            if (responseBodyObj == null) {
                throw new IOException("Response body is null");
            }
            JSONObject responseBody = new JSONObject(responseBodyObj.string());
            // 正确解析嵌套结构
            JSONObject result = responseBody.getJSONObject("result");
            if (result == null) {
                throw new IOException("Missing 'result' field in response");
            }

            String taskId = result.getStr("task_id");
            if (taskId == null || taskId.isEmpty()) {
                throw new IOException("Missing or empty 'task_id' in response");
            }

            return taskId;
        }
    }
}